//
//  HEGestureViewController.m
//  huien
//
//  Created by yiban on 2017/5/31.
//  Copyright © 2017年 lcb. All rights reserved.
//

#import "HEGestureManagerViewController.h"
#import "HEGestureViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
@interface HEGestureManagerViewController ()<UITableViewDataSource,UITableViewDelegate,LcbLoginDelegate>
{
    
}
@property(nonatomic,strong)LcbUITableView *lcbTableView;
@property(nonatomic,strong) UISwitch *gestureSwitch;
@property(nonatomic,strong) UISwitch *touchSwitch;
@property(nonatomic,assign)NSInteger gestureSwitchTag;
@property(nonatomic,assign)NSInteger touchSwitchTag;
@property (weak) id<LcbLoginDelegate> delegate;
+ (instancetype)newController;
@end

@implementation HEGestureManagerViewController
@synthesize lcbTableView=_lcbTableView;
@synthesize gestureSwitch=_gestureSwitch;
@synthesize touchSwitch=_touchSwitch;
@synthesize gestureSwitchTag=_gestureSwitchTag;
@synthesize touchSwitchTag=_touchSwitchTag;

+ (instancetype)newController
{
    return [super new];
}
+ (instancetype)newWithDelegate:(id<LcbLoginDelegate>)delegate
{
    HEGestureManagerViewController *viewController = [HEGestureManagerViewController newController];
    
    if (viewController) {
        viewController.delegate = delegate;
    }
    
    return viewController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"手势管理";
    [self initTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *patternStatus =[[NSUserDefaults standardUserDefaults] objectForKey:@"patternStatus"];
    self.gestureSwitchTag =[patternStatus integerValue];
    NSString *fingerprintStatus =[[NSUserDefaults standardUserDefaults] objectForKey:@"fingerprintStatus"];
    self.touchSwitchTag =[fingerprintStatus integerValue];
    if (_lcbTableView) {
        [_lcbTableView reloadData];
    }
}
-(void)dealloc
{
    if (_lcbTableView) {
        [_lcbTableView removeFromSuperview];
        _lcbTableView=nil;
    }
    [LcbLog log:@"HEGestureManagerViewController--------->dealloc"];
}
#pragma mark - tableview delegate
-(void)initTableView
{
    //
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20, 60, 44);
    backButton.tag =100;
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    //
    if (_lcbTableView) {
        [_lcbTableView removeFromSuperview];
        _lcbTableView=nil;
    }
    _lcbTableView =[[LcbUITableView alloc] initWithFrame:CGRectMake(0, YB_HeaderHeight, SCREEN_WIDTH, SCREEN_HEIGHT-YB_HeaderHeight) style:UITableViewStyleGrouped];
    _lcbTableView.dataSource=self;
    _lcbTableView.delegate=self;
    _lcbTableView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_lcbTableView];
}
-(void)clickNavEvent:(id)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(userDidCancel)]) {
        [_delegate userDidCancel];
    }
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 1;
    }else if(section==1)
    {
        return 2;
    }
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return LcbHEIGHT(40);
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        return @"开启以后，可以使用手势密码和指纹识别登录";
    }
    return @"";
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section==1)
    {
        return LcbHEIGHT(40);
    }
    return LcbHEIGHT(10);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return LcbHEIGHT(10);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (cell == nil) {
        cell = [[UITableViewCell  alloc]initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:@"UITableViewCell"];
        if (indexPath.section==1 && indexPath.row==1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }

    if (indexPath.section==0) {
        cell.textLabel.text=@"开启手势密码";
        _gestureSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
        _gestureSwitch.tag = 1;
   
        if (self.gestureSwitchTag==1) {
            _gestureSwitch.on = YES;
        }else{
            _gestureSwitch.on = NO;
        }
        
        [_gestureSwitch addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = _gestureSwitch;
        _gestureSwitch=nil;
    }else if(indexPath.section==1)
    {
        if (indexPath.row==0) {
            cell.textLabel.text=@"开启指纹识别";
            _touchSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
            _touchSwitch.tag = 2;
            if (self.touchSwitchTag==1) {
                _touchSwitch.on = YES;
            }else{
                _touchSwitch.on = NO;
            }
            
            [_touchSwitch addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
            cell.accessoryView = _touchSwitch;
            _touchSwitch=nil;
        }else if (indexPath.row==1)
        {
            cell.textLabel.text=@"修改手势密码";
        }
        
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1)
    {
        if (indexPath.row==1)
        {
            HEGestureViewController *gestview =[HEGestureViewController newWithDelegate:self];
            if (self.gestureSwitchTag==1) {
                gestview.type=2;
            }else{
                gestview.type=1;
            }
            [self.navigationController pushViewController:gestview animated:YES];
        }
        
    }
}
- (void)updateSwitchAtIndexPath:(id)sender {
    
    UISwitch *switchView = (UISwitch *)sender;
    switch (switchView.tag) {
        case 1:
        {
            if ([switchView isOn])
            {
                HEGestureViewController *gestview =[HEGestureViewController newWithDelegate:self];
                gestview.type=1;
                [self.navigationController pushViewController:gestview animated:YES];
            }else
            {
                [self closeSwitch:1];
            }
        }
            break;
        case 2:
        {
            if ([switchView isOn])
            {
                //do something..
                LAContext *laContext = [[LAContext alloc]init];
                NSError *err = nil;
                BOOL isSupport = [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&err];
                if (isSupport)
                {
                    [laContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"放置指纹" reply:^(BOOL success, NSError *error) {
                        if (success) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [self openfingerPrintLock];
                                [self.lcbTableView reloadData];
                            });
                        }
                    }];
                }
                
            }else{
                [self closeSwitch:2];
                [self.lcbTableView reloadData];
            }
            
        }
            break;
        default:
            break;
    }
   
    
}
-(void)userLoginOK:(id)userinfo
{
    
}
-(void)userDidCancel
{
    
}
-(void)userLoginFail
{
    
}
-(void)openfingerPrintLock
{
    SessionModel *sessionModel =[HEShare sessionModel];
    if (sessionModel==nil) {
        return;
    }
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:sessionModel.sessionId forKey:@"sessionId"];
    [dict setValue:[NSString stringWithFormat:@"%ld",(long)sessionModel.session_user.userId] forKey:@"userId"];
    [dict setValue:@"1" forKey:@"fingerPrintStatus"];
    __weak typeof(self) weakSelf = self;
    [HEApi openfingerPrintLockWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
        if (response) {
            if ([response isKindOfClass:[LcbBaseModel class]]) {
                LcbBaseModel *baseModel = (LcbBaseModel*)response;
                if (baseModel.code>0) {
                    [[NativeRouter sharedNativeRouter] codeHander:weakSelf params:baseModel completion:^(id obj) {
                        
                    }];
                }else{
                    [YBToast showWithText:errorMsg];
                    weakSelf.touchSwitchTag =1;
                     [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"fingerprintStatus"];
                     [[NSUserDefaults standardUserDefaults] synchronize];
                    [weakSelf.lcbTableView reloadData];
                }
                
            }
        }
        
    }];
}
-(void)closeSwitch:(int)type
{
    SessionModel *sessionModel =[HEShare sessionModel];
    if (sessionModel==nil) {
        return;
    }
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:sessionModel.sessionId forKey:@"sessionId"];
    [dict setValue:[NSString stringWithFormat:@"%ld",(long)sessionModel.session_user.userId] forKey:@"userId"];
    if (type==1) {
        [dict setValue:@"0" forKey:@"patternStatus"];
        __weak typeof(self) weakSelf = self;
        [HEApi closePatternLockWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
            if (response) {
                if ([response isKindOfClass:[LcbBaseModel class]]) {
                    LcbBaseModel *baseModel = (LcbBaseModel*)response;
                    if (baseModel.code>0) {
                        [[NativeRouter sharedNativeRouter] codeHander:weakSelf params:baseModel completion:^(id obj) {
                            
                        }];
                    }else{
                        [YBToast showWithText:errorMsg];
                        weakSelf.gestureSwitchTag =0;
                        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:@"patternStatus"];
                         [[NSUserDefaults standardUserDefaults] synchronize];
                        [weakSelf.lcbTableView reloadData];
                    }
                    
                }
            }
            
        }];
    }else if (type==2){
        [dict setValue:@"0" forKey:@"fingerPrintStatus"];
        __weak typeof(self) weakSelf = self;
        [HEApi closeFingerPrintLockWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
            if (response) {
                if ([response isKindOfClass:[LcbBaseModel class]]) {
                    LcbBaseModel *baseModel = (LcbBaseModel*)response;
                    if (baseModel.code>0) {
                        [[NativeRouter sharedNativeRouter] codeHander:weakSelf params:baseModel completion:^(id obj) {
                            
                        }];
                    }else{
                        [YBToast showWithText:errorMsg];
                        weakSelf.touchSwitchTag =0;
                        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:@"fingerprintStatus"];
                         [[NSUserDefaults standardUserDefaults] synchronize];
                        [weakSelf.lcbTableView reloadData];
                    }
                    
                }
            }
            
        }];
    }
   
}
@end
